package cConfig

import (
	"##PROJECT##/core/cHelper"
	"errors"
	"io/ioutil"
	"reflect"
	"strings"
)

func initFile() {
	confPath, err := GetConf("ConfigCenterConf.Channels.File.Path")
	if err != nil {
		confPath = configContainer.path
	}
	if !strings.HasPrefix(confPath.(string), "/") {
		confPath = configContainer.path + "/" + confPath.(string)
	}
	confPath = strings.TrimRight(confPath.(string), "/")

	configContainer.configCenter.fileDriver = confPath.(string)

	listeners, err := GetConf("ConfigCenterConf.Channels.File.Listeners")
	if err != nil {
		return
	}
	len := reflect.ValueOf(listeners).Len()
	if len > 0 {
		for i := 0; i < len; i++ {
			fileNameIndex := "ConfigCenterConf.Channels.File.Listeners." + cHelper.ToString(i) + ".Data"
			confNameIndex := "ConfigCenterConf.Channels.File.Listeners." + cHelper.ToString(i) + ".Conf"

			fileName, err1 := GetConf(fileNameIndex)
			confName, err2 := GetConf(confNameIndex)
			if err1 != nil || err2 != nil {
				continue
			}

			if fileName.(string) != "" && confName.(string) != "" {
				configContainer.configCenter.listeners[confName.(string)] = fileName.(string)
			}
		}
	}
}

func readFile(name string) ([]byte, error) {
	if _, ok := configContainer.configCenter.listeners[name]; ok {
		confPath := configContainer.configCenter.fileDriver + "/" + configContainer.configCenter.listeners[name]
		if !cHelper.IsExistsPath(confPath) {
			return nil, errors.New("config center read file config err: " + confPath + " is not exists")
		}
		content, err := ioutil.ReadFile(confPath)
		return content, err
	} else {
		return nil, errors.New("config center read file config err: " + name + " listener is not exists")
	}
}
